package edu.tcc.iot.persistence.dao.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.tcc.iot.domain.User;
import edu.tcc.iot.persistence.dao.IUserDAO;
import edu.tcc.iot.utils.Configuration;

public class UserDAO implements IUserDAO {

	private static final String PATH = Configuration.getInstance().getProperty("users.config");
	private static final List<User> users = new ArrayList<User>();
	
	public UserDAO(){
		initialize();
	}
	
	public List<User> getUsers() {
		return users;
	}
	
	private void initialize(){
		try {
			
			File fXmlFile = new File(PATH);
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();

			NodeList nList = doc.getElementsByTagName("user");
			
			for (int temp = 0; temp < nList.getLength(); temp++) {

				Node node = nList.item(temp);

				if (node.getNodeType() == Node.ELEMENT_NODE) {

					Element element = (Element) node;
					users.add(new User(element.getAttribute("name"), element.getAttribute("email")));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
